<template>
  <view class="posts-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="title">考研社区</view>
      <view class="subtitle">分享你的备考心得</view>
    </view>

    <!-- 帖子列表 -->
    <view class="posts-list">
      <view class="post-item" v-for="post in posts" :key="post.id" :data-post-id="post.id">
        <!-- 帖子头部 -->
        <view class="post-header">
          <image class="avatar" :src="post.avatar" mode="aspectFill"></image>
          <view class="user-info">
            <text class="username">{{ post.username }}</text>
            <text class="post-time">{{ formatDate(post.createTime) }}</text>
          </view>
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
          <text class="content-text">{{ post.content }}</text>

          <!-- 视频展示 -->
          <view class="post-video" v-if="post.isLike">
            <video
              class="video-player"
              :src="post.isLike"
              :poster="post.images"
              object-fit="cover"
              controls
              @error="handleVideoError"
            ></video>
          </view>

          <!-- 图片展示 -->
          <view class="post-images" v-else-if="post.images">
            <image
              class="post-image"
              :src="post.images"
              mode="aspectFill"
              @tap="previewImage(post.images)"
            ></image>
          </view>
        </view>

        <!-- 互动区域 -->
        <view class="post-actions">
          <view class="action-item" @tap="likePostAction(post.id)">
            <template v-if="isPostLiked(post.id)">
              <text class="action-icon liked">👍</text>
            </template>
            <template v-else>
              <text class="action-text">点赞</text>
            </template>
            <text class="like-count" v-if="post.like > 0">{{ post.like }}</text>
          </view>
          <view class="action-item" @tap="toggleComments(post.id)">
            <text class="action-icon">💬</text>
            <text class="action-text">评论 {{ post.arrayComment?.length || 0 }}</text>
          </view>
          <view class="action-item" @tap="favoritePostAction(post.id)">
            <text class="action-icon">⭐</text>
            <text class="action-text">收藏</text>
          </view>
        </view>

        <!-- 评论区 -->
        <view class="comments-section" v-if="post.showComments && post.arrayComment?.length">
          <view class="comment-item" v-for="comment in post.arrayComment" :key="comment.id">
            <view class="comment-content-row">
              <text
                class="comment-username"
                @tap="replyToUser(post.id, comment.username, comment.userId)"
                >{{ comment.username }}</text
              ><text class="colon">：</text>
              <text v-if="comment.replyToUsername" class="comment-reply">
                回复
                <text
                  class="reply-name"
                  @tap="replyToUser(post.id, comment.replyToUsername, comment.replyToUserId)"
                  >@{{ comment.replyToUsername }}</text
                >
              </text>
              <text class="comment-text">{{ comment.content }}</text>
            </view>
          </view>
        </view>

        <!-- 评论输入框 -->
        <view class="comment-input-area" v-if="post.showComments">
          <view class="comment-input-row">
            <input
              class="comment-input"
              :placeholder="
                replyInfo[post.id] ? `回复 @${replyInfo[post.id].username}` : '说点什么吧...'
              "
              v-model="commentText[post.id]"
              confirm-type="send"
              @confirm="submitComment(post.id)"
            />
            <view v-if="replyInfo[post.id]" class="cancel-reply" @tap="clearReplyInfo(post.id)"
              >×</view
            >
            <view class="send-btn" @tap="submitComment(post.id)">发送</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 无数据提示 -->
    <view class="empty-container" v-if="posts.length === 0">
      <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无动态，快来发布第一条吧</text>
    </view>

    <!-- 发布按钮 -->
    <view class="floating-button" @tap="navigateToPublish">
      <text class="plus-icon">+</text>
    </view>
  </view>
</template>

<script>
import { queryPostsShi } from '@/api/post'
import { insertComment } from '@/api/post'
import { likePost, findLikes } from '@/api/post'

export default {
  data() {
    return {
      posts: [],
      commentText: {}, // 存储每个帖子的评论文本
      isLoading: false,
      replyInfo: {}, // 存储回复信息，格式: {postId: {userId: 1, username: '用户名'}}
      likedPostIds: [], // 存储已点赞的帖子ID
    }
  },

  onLoad() {
    this.fetchPosts()
    this.fetchLikedPosts()
  },

  onShow() {
    this.fetchPosts()
    this.fetchLikedPosts()
  },

  onPullDownRefresh() {
    this.fetchPosts()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },

  methods: {
    // 获取帖子数据
    fetchPosts() {
      if (this.isLoading) return

      this.isLoading = true
      uni.showLoading({ title: '加载中...' })

      queryPostsShi()
        .then((res) => {
          console.log('获取动态数据:', res)
          this.isLoading = false
          uni.hideLoading()

          if (res.statusCode === 200 && res.data) {
            const result = res.data
            if (result.code === 200) {
              // 将获取的数据转换为页面需要的格式
              this.posts = result.data.map((post) => {
                return {
                  ...post,
                  showComments: false,
                }
              })
            } else {
              uni.showToast({
                title: result.info || '获取数据失败',
                icon: 'none',
              })
              // 使用测试数据
              this.useTestData()
            }
          } else {
            // 请求失败，使用测试数据
            uni.showToast({
              title: '网络连接失败',
              icon: 'none',
            })
            this.useTestData()
          }
        })
        .catch((err) => {
          console.error('获取动态失败:', err)
          this.isLoading = false
          uni.hideLoading()
          // 异常时使用测试数据
          this.useTestData()
        })
    },

    // 使用测试数据
    useTestData() {
      this.posts = [
        {
          id: 15,
          username: 'ln',
          avatar:
            'https://gulimalld.oss-cn-beijing.aliyuncs.com/image/2025-01-20/3e73b336-9f4a-4a1f-9932-56685ee0eeab.jpg',
          content: 'java基础知识总结，希望对大家有帮助，考研加油！',
          images:
            'https://gulimalld.oss-cn-beijing.aliyuncs.com/image/2024-12-26/36d14185-b5b2-4827-9dd8-5b8828c77017.jpeg',
          createTime: '2025-04-01T00:54:37',
          showComments: false,
          arrayComment: [
            {
              id: 35,
              postId: 15,
              userId: 7,
              username: 'ln',
              replyToUserId: null,
              replyToUsername: null,
              content: '这篇总结写得非常好，感谢分享！',
              createTime: '2025-04-01T09:32:12',
            },
          ],
        },
      ]

      uni.showToast({
        title: '使用测试数据',
        icon: 'none',
      })
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''

      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr

        const now = new Date()
        const diff = now - date

        // 24小时内，显示几小时前
        if (diff < 24 * 60 * 60 * 1000) {
          const hours = Math.floor(diff / (60 * 60 * 1000))
          if (hours === 0) {
            const minutes = Math.floor(diff / (60 * 1000))
            return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
          }
          return `${hours}小时前`
        }

        // 一周内，显示周几
        if (diff < 7 * 24 * 60 * 60 * 1000) {
          const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
          return days[date.getDay()]
        }

        // 超过一周，显示具体日期
        return `${date.getMonth() + 1}月${date.getDate()}日`
      } catch (e) {
        console.error('日期格式化错误:', e)
        return dateStr
      }
    },

    // 查看大图
    previewImage(url) {
      if (!url) return

      uni.previewImage({
        urls: [url],
        current: url,
      })
    },

    // 切换评论区显示/隐藏
    toggleComments(postId) {
      this.posts = this.posts.map((post) => {
        if (post.id === postId) {
          return {
            ...post,
            showComments: !post.showComments,
          }
        }
        return post
      })
    },

    // 设置回复目标
    replyToUser(postId, username, userId) {
      this.$set(this.replyInfo, postId, {
        userId,
        username,
      })

      // 聚焦到输入框 - 改用uni-app的方式
      setTimeout(() => {
        // 将目标和提示消息显示出来即可，不需要强制聚焦
        uni.showToast({
          title: `回复 @${username}`,
          icon: 'none',
          duration: 1000,
        })
      }, 100)
    },

    // 清除回复信息
    clearReplyInfo(postId) {
      try {
        // 第一种方法：使用ES6 spread语法创建新对象
        const newReplyInfo = { ...this.replyInfo }
        delete newReplyInfo[postId]
        this.replyInfo = newReplyInfo

        // 如果上面的方法失败，可以使用下面的替代方案
        // this.replyInfo[postId] = undefined;
      } catch (error) {
        console.error('清除回复信息失败:', error)
        // 直接将对应项设为undefined
        this.replyInfo[postId] = undefined
      }
    },

    // 提交评论
    submitComment(postId) {
      const comment = this.commentText[postId]
      if (!comment || comment.trim() === '') {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'none',
        })
        return
      }

      // 获取回复信息
      const replyTo = this.replyInfo[postId]

      // 使用API发送评论
      const commentData = {
        postId: postId,
        content: comment,
        replyToUserId: replyTo ? replyTo.userId : null,
        replyToUsername: replyTo ? replyTo.username : null,
      }

      // 先清空评论文本和回复信息，提升用户体验
      const commentContent = this.commentText[postId]
      this.$set(this.commentText, postId, '')
      this.clearReplyInfo(postId)

      uni.showLoading({
        title: '提交中...',
      })

      insertComment(commentData)
        .then((res) => {
          uni.hideLoading()
          console.log('评论提交响应:', res)
          const response = res.data

          if (response && response.code === 200) {
            uni.showToast({
              title: '评论成功',
              icon: 'success',
              duration: 1500,
            })

            // 短暂延迟后刷新数据，确保服务器已处理完成
            setTimeout(() => {
              this.fetchPosts()
            }, 300)
          } else {
            // 恢复之前的评论内容，允许用户重试
            this.$set(this.commentText, postId, commentContent)
            if (replyTo) {
              this.$set(this.replyInfo, postId, replyTo)
            }

            uni.showToast({
              title: response?.info || '评论失败',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          uni.hideLoading()
          console.error('评论提交错误:', err)

          // 恢复之前的评论内容，允许用户重试
          this.$set(this.commentText, postId, commentContent)
          if (replyTo) {
            this.$set(this.replyInfo, postId, replyTo)
          }

          uni.showToast({
            title: '评论失败，请稍后再试',
            icon: 'none',
          })
        })
    },

    // 获取已点赞的帖子列表
    fetchLikedPosts() {
      findLikes()
        .then((res) => {
          console.log('获取点赞数据响应:', res)

          if (res.statusCode === 200 && res.data) {
            const result = res.data
            if (result.code === 200 && Array.isArray(result.data)) {
              // 清空之前的点赞ID列表
              this.likedPostIds = []

              // 提取已点赞的帖子ID
              result.data.forEach((like) => {
                if (like.isLike === '是') {
                  // 确保将postId转换为数字类型
                  const postId = Number(like.postId)
                  if (!isNaN(postId) && !this.likedPostIds.includes(postId)) {
                    this.likedPostIds.push(postId)
                  }
                }
              })

              console.log('已点赞的帖子ID列表:', this.likedPostIds)

              // 更新帖子列表中的点赞状态
              this.updatePostsLikeStatus()
            } else {
              console.warn('获取点赞数据异常:', result)
            }
          }
        })
        .catch((err) => {
          console.error('获取点赞数据失败:', err)
        })
    },

    // 更新帖子的点赞状态
    updatePostsLikeStatus() {
      if (this.posts.length === 0) return

      // 遍历帖子，标记已点赞状态
      this.posts = this.posts.map((post) => {
        return {
          ...post,
          isLiked: this.likedPostIds.includes(post.id),
        }
      })
    },

    // 判断帖子是否已点赞
    isPostLiked(postId) {
      console.log(`检查帖子ID ${postId} 是否点赞, likedPostIds:`, this.likedPostIds)
      // 确保进行数字类型比较
      return this.likedPostIds.includes(Number(postId))
    },

    // 点赞动态
    likePostAction(postId) {
      // 转换为数字类型确保一致性
      postId = Number(postId)

      // 检查当前点赞状态
      const isCurrentlyLiked = this.isPostLiked(postId)
      console.log(`点赞操作: postId=${postId}, 当前状态=${isCurrentlyLiked ? '已点赞' : '未点赞'}`)

      likePost(postId)
        .then((res) => {
          console.log('点赞操作响应:', res)
          if (res.statusCode === 200 && res.data) {
            const result = res.data
            if (result.code === 200) {
              // 更新本地点赞状态
              const postIndex = this.posts.findIndex((p) => p.id === postId)

              if (postIndex !== -1) {
                // 更新点赞数
                if (!isCurrentlyLiked) {
                  // 点赞数+1
                  this.$set(this.posts[postIndex], 'like', (this.posts[postIndex].like || 0) + 1)

                  // 添加到已点赞列表
                  if (!this.likedPostIds.includes(postId)) {
                    this.likedPostIds.push(postId)
                  }

                  uni.showToast({
                    title: '点赞成功',
                    icon: 'success',
                  })
                } else {
                  // 点赞数-1，但不低于0
                  const currentLikes = this.posts[postIndex].like || 0
                  this.$set(this.posts[postIndex], 'like', Math.max(0, currentLikes - 1))

                  // 从已点赞列表移除
                  const index = this.likedPostIds.indexOf(postId)
                  if (index !== -1) {
                    this.likedPostIds.splice(index, 1)
                  }

                  uni.showToast({
                    title: '取消点赞',
                    icon: 'success',
                  })
                }

                // 更新列表状态
                this.updatePostsLikeStatus()
              }
            } else {
              uni.showToast({
                title: result.info || '操作失败',
                icon: 'none',
              })
            }
          } else {
            uni.showToast({
              title: '网络错误',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.error('点赞操作失败:', err)
          uni.showToast({
            title: '操作失败，请稍后再试',
            icon: 'none',
          })
        })
    },

    // 收藏动态
    favoritePostAction(postId) {
      uni.showToast({
        title: '收藏成功',
        icon: 'success',
      })
    },

    // 跳转到发布页面
    navigateToPublish() {
      uni.navigateTo({
        url: '/pages/publish/publish',
      })
    },

    // 处理视频加载错误
    handleVideoError(err) {
      console.error('视频加载失败:', err)
      uni.showToast({
        title: '视频加载失败',
        icon: 'none',
      })
    },
  },
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

.posts-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;

  .header {
    height: 200rpx;
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    border-radius: 0 0 40rpx 40rpx;
    padding: 60rpx 40rpx 30rpx;
    color: #fff;

    .title {
      font-size: 40rpx;
      font-weight: bold;
    }

    .subtitle {
      font-size: 26rpx;
      margin-top: 10rpx;
      opacity: 0.8;
    }
  }

  .posts-list {
    padding: 30rpx;
    margin-top: -60rpx;

    .post-item {
      background-color: #fff;
      border-radius: 20rpx;
      margin-bottom: 30rpx;
      padding: 30rpx;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
      position: relative;

      .post-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          background-color: #eee;
        }

        .user-info {
          margin-left: 20rpx;

          .username {
            font-size: 28rpx;
            font-weight: 500;
            color: #333;
          }

          .post-time {
            font-size: 24rpx;
            color: #999;
            margin-top: 6rpx;
            display: block;
          }
        }
      }

      .post-content {
        margin-bottom: 20rpx;

        .content-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.6;
        }

        .post-video {
          margin-top: 20rpx;
          width: 100%;
          border-radius: 12rpx;
          overflow: hidden;
          background-color: #000;

          .video-player {
            width: 100%;
            height: 400rpx;
            border-radius: 12rpx;
          }
        }

        .post-images {
          margin-top: 20rpx;

          .post-image {
            width: 100%;
            height: 350rpx;
            border-radius: 12rpx;
            background-color: #f5f5f5;
          }
        }
      }

      .post-actions {
        display: flex;
        justify-content: space-around;
        padding: 20rpx 0;
        border-top: 1px solid #f5f5f5;
        border-bottom: 1px solid #f5f5f5;

        .action-item {
          display: flex;
          align-items: center;
          margin-right: 20rpx;
          padding: 6rpx 10rpx;
          border-radius: 6rpx;
          min-width: 80rpx;
          justify-content: center;
        }

        .action-icon {
          font-size: 36rpx;
          transition: all 0.3s ease;
        }

        .action-text {
          font-size: 28rpx;
          color: #666;
        }

        .liked {
          color: #ff4757;
          font-size: 40rpx;
          transform: scale(1.2);
          transition: all 0.3s ease;
          text-shadow: 0 2rpx 4rpx rgba(255, 71, 87, 0.3);
        }

        .like-count {
          font-size: 24rpx;
          color: #999;
          margin-left: 4rpx;
          min-width: 24rpx;
          text-align: center;
        }

        .liked + .like-count {
          color: #ff4757;
          font-weight: bold;
        }
      }

      .comments-section {
        margin-top: 20rpx;
        background-color: #f9f9f9;
        border-radius: 16rpx;
        padding: 20rpx;

        .comment-item {
          padding: 16rpx 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .comment-content-row {
            display: flex;
            flex-wrap: wrap;
            align-items: center;

            .comment-username {
              font-size: 26rpx;
              font-weight: 500;
              color: #fff;
              background-color: $theme-color;
              padding: 4rpx 12rpx;
              border-radius: 24rpx;

              /* 添加点击效果 */
              &:active {
                opacity: 0.7;
              }
            }

            .colon {
              font-size: 26rpx;
              color: #333;
              margin: 0 4rpx;
            }

            .comment-reply {
              font-size: 24rpx;
              color: #666;
              margin-right: 8rpx;

              .reply-name {
                color: $theme-color;

                /* 添加点击效果 */
                &:active {
                  opacity: 0.7;
                }
              }
            }

            .comment-text {
              font-size: 26rpx;
              color: #333;
              line-height: 1.5;
              flex: 1;
            }
          }
        }
      }

      .comment-input-area {
        display: flex;
        margin-top: 20rpx;

        .comment-input-row {
          display: flex;
          align-items: center;
          width: 100%;
        }

        .comment-input {
          flex: 1;
          height: 70rpx;
          background-color: #f5f5f5;
          border-radius: 35rpx;
          padding: 0 30rpx;
          font-size: 26rpx;
        }

        .cancel-reply {
          font-size: 32rpx;
          color: #999;
          padding: 0 10rpx;
          margin: 0 5rpx;
          &:active {
            opacity: 0.7;
          }
        }

        .send-btn {
          width: 110rpx;
          height: 70rpx;
          background-color: $theme-color;
          color: #fff;
          border-radius: 35rpx;
          font-size: 26rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 10rpx;
        }
      }
    }
  }

  .empty-container {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .floating-button {
    position: fixed;
    right: 40rpx;
    bottom: 140rpx;
    width: 100rpx;
    height: 100rpx;
    background-color: $theme-color;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 8rpx 16rpx rgba(147, 112, 219, 0.4);
    z-index: 10;

    .plus-icon {
      color: #fff;
      font-size: 60rpx;
      font-weight: bold;
    }
  }
}
</style>
